<script>
  import { onMount } from "svelte";
  import { writable } from "svelte/store";
  import { getTodos, addTodo, deleteTodo } from "./api";

  let todos = writable([]);
  let newTodo = "";

  onMount(async () => {
    todos.set(await getTodos());
  });

  const add = async () => {
    await addTodo({
      title: newTodo,
      completed: false,
    });
    todos.set(await getTodos());
    newTodo = "";
  };

  const remove = async (id) => {
    await deleteTodo(id);
    todos.set(await getTodos());
  };

  const toggle = async (todo) => {
    todo.completed = !todo.completed;
    await addTodo(todo);
    todos.set(await getTodos());
  };

  const clearCompleted = async () => {
    (await todos)
      .filter((todo) => todo.completed)
      .forEach(async (todo) => {
        await deleteTodo(todo.id);
      });
    todos.set(await getTodos());
  };

  const remaining = () => {
    return todos.filter((todo) => !todo.completed).length;
  };

  const allCompleted = () => {
    return todos.filter((todo) => !todo.completed).length === 0;
  };

  const toggleAll = async () => {
    (await todos).forEach(async (todo) => {
      todo.completed = !allCompleted();
      await addTodo(todo);
    });
    todos.set(await getTodos());
  };

  const filter = writable("all");
  const filteredTodos = () => {
    switch (filter) {
      case "active":
        return todos.filter((todo) => !todo.completed);
      case "completed":
        return todos.filter((todo) => todo.completed);
      default:
        return todos;
    }
  };

  const pluralize = (count, word) => {
    return count === 1 ? word : word + "s";
  };

  const showClearButton = () => {
    return todos.filter((todo) => todo.completed).length > 0;
  };

  const showMain = () => {
    return todos.length > 0;
  };

  const showFooter = () => {
    return todos.length > 0;
  };

  const showFilters = () => {
	return todos.length > 0;
  };

  const showAllFilter = () => {
	return filter === "all";
  };

  const showActiveFilter = () => {

	return filter === "active";
  };

  const showCompletedFilter = () => {
	return filter === "completed";
  };
</script>
<div class="todolist">
  <h1>todos</h1>
  <input
    class="new-todo"
    placeholder="What needs to be done?"
    bind:value={newTodo}
    on:keydown={async (e) => {
      if (e.key === "Enter") {
        await add();
      }
    }}
  />
  {#if showMain()}
    <section class="main">
      <input
        class="toggle-all"
        type="checkbox"
        bind:checked={allCompleted()}
        on:click={toggleAll}
      />
      <ul class="todo-list">
        {#each filteredTodos() as todo}
          <li class:completed={todo.completed}>
            <div class="view">
              <input
                class="toggle"
                type="checkbox"
                bind:checked={todo.completed}
                on:click={async () => {
                  await toggle(todo);
                }}
              />
              <label>{todo.title}</label>
              <button
                class="destroy"
                on:click={async () => {
                  await remove(todo.id);
                }}
              />
            </div>
          </li>
        {/each}
      </ul>
    </section>
  {/if}
  {#if showFooter()}
    <footer class="footer">
      <span class="todo-count">
        <strong>{remaining()}</strong> {pluralize(remaining(), "item")} left
      </span>
      {#if showFilters()}
        <ul class="filters">
          <li>
            <a
              class:selected={showAllFilter()}
              on:click={setAllFilter}
              >All</a
            >
          </li>
          <li>
            <a
              class:selected={showActiveFilter()}
              on:click={setActiveFilter}
              >Active</a
            >
          </li>
          <li>
            <a
              class:selected={showCompletedFilter()}
              on:click={setCompletedFilter}
              >Completed</a
            >
          </li>
        </ul>
      {/if}
      {#if showClearButton()}
        <button
          class="clear-completed"
          on:click={async () => {
            await clearCompleted();
          }}
        >
          Clear completed
        </button>
      {/if}
    </footer>
  {/if}
</div>

<style>
  .todolist {
    background: #fff;
    margin: 130px 0 40px 0;
    position: relative;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
      0 25px 50px 0 rgba(0, 0, 0, 0.1);
  }

  .todolist input::-webkit-input-placeholder {
    font-style: italic;
    font-weight: 300;
    color: #e6e6e6;
  }

  .todolist input::-moz-placeholder {
    font-style: italic;
    font-weight: 300;
    color: #e6e6e6;
  }

  .todolist input::input-placeholder {
    font-style: italic;
    font-weight: 300;
    color: #e6e6e6;
  }

  .todolist input::ms-input-placeholder {
    font-style: italic;
    font-weight: 300;
    color: #e6e6e6;
  }

  .todolist h1 {
    position: absolute;
    top: -155px;
    width: 100%;
    font-size: 100px;
    font-weight: 100;
    text-align: center;
    color: rgba(175, 47, 47, 0.15);
    -webkit-text-rendering: optimizeLegibility;
    -moz-text-rendering: optimizeLegibility;
    text-rendering: optimizeLegibility;
  }

  .todolist .new-todo {
    position: relative;
    margin: 0;
    width: 100%;
    font-size: 24px;
    font-family: inherit;
    font-weight: inherit;
    line-height: 1.4em;
    border: 0;
    color: inherit;
    padding: 16px 16px 16px 60px;
    border: 1px solid #999;
    box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
    box-sizing: border-box;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }

  .todolist .new-todo:focus {
    outline: none;
  }

  .
</style>
